package cn.iocoder.yudao.module.wms.service.productionorder;

import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.bpm.api.task.BpmProcessInstanceApi;
import cn.iocoder.yudao.module.bpm.api.task.dto.BpmProcessInstanceCreateReqDTO;
import cn.iocoder.yudao.module.bpm.dal.mysql.task.ActHiProcinstMapper;
import cn.iocoder.yudao.module.bpm.enums.task.BpmTaskStatusEnum;
import cn.iocoder.yudao.module.wms.dal.redis.RedisKeyConstants;
import cn.iocoder.yudao.module.wms.dal.redis.serialNumber.WmsSerialNumberRedisDAO;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.wms.controller.admin.productionorder.vo.*;
import cn.iocoder.yudao.module.wms.dal.dataobject.productionorder.ProductionOrderDO;
import cn.iocoder.yudao.module.wms.dal.dataobject.productionorder.ProductionOrdersDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.wms.dal.mysql.productionorder.ProductionOrderMapper;
import cn.iocoder.yudao.module.wms.dal.mysql.productionorder.ProductionOrdersMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.wms.enums.ErrorCodeConstants.*;

/**
 * 生产任务单主表 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class ProductionOrderServiceImpl implements ProductionOrderService {

    @Resource
    private ProductionOrderMapper productionOrderMapper;
    @Resource
    private ProductionOrdersMapper productionOrdersMapper;
    @Resource
    private WmsSerialNumberRedisDAO serialNumberRedisDAO;
    @Resource
    private BpmProcessInstanceApi processInstanceApi;
    @Resource
    private ActHiProcinstMapper actHiProcinstMapper;
    public static final String PROCESS_KEY = "productionOrder-flowable";

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createProductionOrder(ProductionOrderSaveReqVO createReqVO) {
        // 插入
        String serialNumber = serialNumberRedisDAO.generate(WmsSerialNumberRedisDAO.POMAIN_SERIAL_PREFIX, RedisKeyConstants.SERIALProductionOrder);

        ProductionOrderDO productionOrder = BeanUtils.toBean(createReqVO, ProductionOrderDO.class)
                .setSerialNumber(serialNumber).setNumber(getSum(createReqVO))
                .setStatus(BpmTaskStatusEnum.SUBMIT.getStatus());
        productionOrderMapper.insert(productionOrder);

        // 插入子表
        createProductionOrdersList(productionOrder.getId(), createReqVO.getProductionOrderss());

            // 返回
        return productionOrder.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProductionOrder(ProductionOrderSaveReqVO updateReqVO) {
        // 校验存在
        validateProductionOrderExists(updateReqVO.getId());
        // 更新
        ProductionOrderDO updateObj = BeanUtils.toBean(updateReqVO, ProductionOrderDO.class);
        productionOrderMapper.updateById(updateObj);
        if (updateReqVO.getProductionOrderss()!=null)
        {
            // 更新子表
            updateProductionOrdersList(updateReqVO.getId(), updateReqVO.getProductionOrderss());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteProductionOrder(Long id) {
        // 校验存在
        validateProductionOrderExists(id);
        // 删除
        productionOrderMapper.deleteById(id);

        // 删除子表
        deleteProductionOrdersByOrderId(id);
    }

    private void validateProductionOrderExists(Long id) {
        if (productionOrderMapper.selectById(id) == null) {
            throw exception(PRODUCTION_ORDER_NOT_EXISTS);
        }
    }

    @Override
    public ProductionOrderDO getProductionOrder(Long id) {
        return productionOrderMapper.selectById(id);
    }

    @Override
    public PageResult<ProductionOrderDO> getProductionOrderPage(ProductionOrderPageReqVO pageReqVO) {
        return productionOrderMapper.selectPage(pageReqVO);
    }

    // ==================== 子表（生产任务单子） ====================

    @Override
    public List<ProductionOrdersDO> getProductionOrdersListByPid(Long pid) {
        return productionOrdersMapper.selectListByPid(pid);
    }

    @Override
    public void updateStatus(ProductionOrderDO productionOrderDO) {
        productionOrderMapper.updateStatus(productionOrderDO);
    }

    @Override
    public ProductionOrderDO findByProcessInstanceId(String processInstanceId) {
        return productionOrderMapper.findByProcessInstanceId(processInstanceId);
    }

    /***
     * 业务流程处理
     */

    @Override
    public void businessProcessing(ProductionOrderDO productionOrderDO, List<ProductionOrdersDO> productionOrdersDOList) {

    }

    @Override
    public List<ProductionOrdersRespVO> findProductionOrdersByPid(Integer pid) {
        return productionOrderMapper.findProductionOrdersByPid(pid);
    }

    @Override
    public ProductionOrdersRespVO findProductionOrdersById(Integer id) {
        return productionOrderMapper.findProductionOrdersById(id);
    }

    @Override
    public void updateProductionOrders(ProductionOrdersRespVO productionOrdersRespVO) {
        productionOrderMapper.updateProductionOrders(productionOrdersRespVO);
    }

    @Override
    public List<ProductionOrdersRespVO> findProductionOrdersOperateList(ProductionOrdersDO productionOrdersDO) {
        return productionOrderMapper.findProductionOrdersOperateList(productionOrdersDO);
    }

    @Override
    public List<ProductionOrderDO> findProductionOrderOperateList() {
        return productionOrderMapper.findProductionOrderOperateList();
    }

    @Override
    public void process(Long id) {
        /***
         * 启动流程
         */

        // 发起 BPM 流程
        Map<String, Object> processInstanceVariables = new HashMap<>();
        String processInstanceId = processInstanceApi.createProcessInstance(SecurityFrameworkUtils.getLoginUserId(),
                new BpmProcessInstanceCreateReqDTO().setProcessDefinitionKey(PROCESS_KEY)
                        .setVariables(processInstanceVariables).setBusinessKey(String.valueOf(id)));

        // 将工作流的编号，更新到 业务表单中
        productionOrderMapper.updateById(new ProductionOrderDO().setId(id).setProcessInstanceId(processInstanceId).setStatus(BpmTaskStatusEnum.RUNNING.getStatus()));
        //将链接加入到ACT_HI_PROCINST表中
        actHiProcinstMapper.updateURLById("/order/productionOrderForm?id=" +id, processInstanceId);

    }

    private void createProductionOrdersList(Long pid, List<ProductionOrdersDO> list) {
        list.forEach(o -> o.setPid(pid));
        productionOrdersMapper.insertBatch(list);
    }

    private void updateProductionOrdersList(Long orderId, List<ProductionOrdersDO> list) {
        deleteProductionOrdersByOrderId(orderId);
        list.forEach(o -> o.setId(null).setUpdater(null).setUpdateTime(null)); // 解决更新情况下：1）id 冲突；2）updateTime 不更新
        createProductionOrdersList(orderId, list);
    }

    private void deleteProductionOrdersByOrderId(Long orderId) {
        productionOrdersMapper.deleteByOrderId(orderId);
    }

    private Double getSum(ProductionOrderSaveReqVO productionOrderSaveReqVO)
    {
        //得到总数量
        Double sum=0.0;
        if (productionOrderSaveReqVO.getProductionOrderss()!=null){
            for (ProductionOrdersDO productionOrdersDO:productionOrderSaveReqVO.getProductionOrderss())
            {
                sum+=productionOrdersDO.getQuantity();
            }
        }
        return sum;
    }

}